package com.hj.hos.service;

import cn.hutool.core.text.CharPool;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.hj.hos.HosService;
import com.hj.hos.properties.HosProperties;

import java.io.ByteArrayInputStream;
import java.io.InputStream;


/**
 * @author hj
 * @Date 2023/4/29
 * @Description: 阿里云存储
 */
public class AliyunHosService extends HosService {

    public AliyunHosService(HosProperties properties) {
        this.properties = properties;
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        OSS client = new OSSClientBuilder().build(properties.getAliyun().getEndPoint(),
                properties.getAliyun().getAccessKeyId(), properties.getAliyun().getAccessKeySecret());
        try {
            client.putObject(properties.getAliyun().getBucketName(), path, inputStream);
        } catch (Exception e) {
            throw new RuntimeException("阿里oss--上传文件失败：", e);
        } finally {
            if (client != null) {
                client.shutdown();
            }
        }
        return properties.getConfig().getDomain() + CharPool.SLASH + path;
    }

}
